# -*- coding: utf-8 -*-
'''
  @author zhanghaisheng
  @date 2021/8/20
  @description get sonar_code_scan result
'''
import os
# import urllib.request
# import urllib.parse
import json
import sys

token = "72e621a6f87890ff71772801ad396d09f78d59b2"

def exec_cmd(cmd):
    if cmd is not None:
        return os.popen(cmd).read()
    else:
        return 'cmd is none!'

# def request(url, method='GET', data=None, header={}):
#     if method == 'GET':
#         request = urllib.request.Request(url)
#         response = urllib.request.urlopen(request)
#         resraw = response.read()
#         return resraw
#     elif method == 'POST':
#         request = urllib.request.Request(url, data.encode('utf-8'), header, method='POST')
#         response = urllib.request.urlopen(request)
#         resraw = response.read()
#         return resraw
#     else:
#         return  None

def get_sonar_meric_number(component, metric_key):
    url_get_metric = 'https://sonar.ecarxgroup.com/api/measures/component?component=' + component + '&metricKeys=' + metric_key
    cmd_get_metric = "curl -u " + token + ":  " + "\'" + url_get_metric + "\'"
    response = exec_cmd(cmd_get_metric)
    if 'value' in response:
        if metric_key == 'new_bugs':
            return json.loads(response)['component']['measures'][0]['periods'][0]['value']
        else:
            return json.loads(response)['component']['measures'][0]['value']
    else:
        return None

def get_sonar_severity_number(componentKeys, severity):
    url_get_severity = 'https://sonar.ecarxgroup.com/api/issues/search?componentKeys=' + componentKeys + '&severities=' + severity
    cmd_get_severity = "curl -u " + token + ":  " + "\'" + url_get_severity + "\'"
    response = exec_cmd(cmd_get_severity)
    if 'total' and 'paging' in response:
        # return json.loads(response.split(',')[0] + '}')['total']
        fixed = len(response.split('FIXED')) - 1  # 已修复问题数
        return str(int(response.split(',')[0].split(':')[1]) - fixed)
    else:
        return None

def get_sonar_status(projectKey):
    url_get_status = 'https://sonar.ecarxgroup.com/api/qualitygates/project_status?projectKey=' + projectKey
    cmd_get_status = "curl -u " + token + ":  " + "\'" + url_get_status + "\'"
    response = exec_cmd(cmd_get_status)
    if 'status' in response:
        return json.loads(response)['projectStatus']['status']
    else:
        return None


def get_sonar_total_result(project_name):
    blocker = get_sonar_severity_number(project_name, 'BLOCKER') # 阻塞数量
    critical = get_sonar_severity_number(project_name, 'CRITICAL') # 严重数量
    major = get_sonar_severity_number(project_name, 'MAJOR') # 主要数量
    minor = get_sonar_severity_number(project_name, 'MINOR') # 次要数量

    bugs = get_sonar_meric_number(project_name, 'bugs') # 本次扫描bug总数
    new_bugs = get_sonar_meric_number(project_name, 'new_bugs') #本次扫描相比上次新增bug数

    status = get_sonar_status(project_name) # sonar平台判断本次扫描结果，OK 或者 ERROR，作为最终扫描结果参考
    sonar_url = 'https://sonar.ecarxgroup.com/dashboard?id=' + project_name #sonar平台项目链接

    print('blocker:' + str(blocker))
    print('critical:' + str(critical))
    print('major:' + str(major))
    print('minor:' + str(minor))
    print('bugs:' + str(bugs))
    print('new_bugs:' + str(new_bugs))
    print('status:' + str(status))
    print('sonar_url:' + str(sonar_url))

    return {"bugs": str(bugs),     # bug数
            "new_bugs": str(new_bugs),      # 新增bug数
            "minor": str(minor),         # 次要
            "major": str(major),         # 主要
            "critical": str(critical),      # 严重
            "blocker": str(blocker),       # 阻塞
            "sonar_url": str(sonar_url)   # sonar平台项目链接
            }


if __name__ == '__main__':
    # print(j['component']['measures'][0]['value'])
    # get_sonar_total_result('admap_ad-assess')
    get_sonar_total_result(sys.argv[1])
    # s = 'hsdkfhkdhfsldjl'
    # # s = '{"total":3,"p":1,"ps":100,"paging":{"pageIndex":1,"pageSize":100,"total":3},"effortTotal":12,"issues":[{"key":"AXtXGT8EBV_LB6M9zWEd","rule":"java:S3516","severity":"BLOCKER","component":"stdci_std-segment-matching-service-app-meta:segment-matching-service/matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","project":"stdci_std-segment-matching-service-app-meta","line":97,"hash":"f69a44a25855a41d7902b3bbadf667ca","textRange":{"startLine":97,"endLine":97,"startOffset":26,"endOffset":54},"flows":[{"locations":[{"component":"stdci_std-segment-matching-service-app-meta:segment-matching-service/matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","textRange":{"startLine":108,"endLine":108,"startOffset":8,"endOffset":20},"msg":"Returned value."},{"component":"stdci_std-segment-matching-service-app-meta:segment-matching-service/matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","textRange":{"startLine":104,"endLine":104,"startOffset":20,"endOffset":32},"msg":"Returned value."}]}],"status":"OPEN","message":"Refactor this method to not always return the same value.","effort":"4min","debt":"4min","author":"","tags":[],"creationDate":"2021-08-18T10:31:02+0800","updateDate":"2021-08-18T10:31:02+0800","type":"CODE_SMELL","scope":"MAIN"},{"key":"AXtR8PE5BV_LB6M9sEDw","rule":"java:S3516","severity":"BLOCKER","component":"stdci_std-segment-matching-service-app-meta:matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","project":"stdci_std-segment-matching-service-app-meta","hash":"f69a44a25855a41d7902b3bbadf667ca","textRange":{"startLine":97,"endLine":97,"startOffset":26,"endOffset":54},"flows":[{"locations":[{"component":"stdci_std-segment-matching-service-app-meta:matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","textRange":{"startLine":108,"endLine":108,"startOffset":8,"endOffset":20},"msg":"Returned value."},{"component":"stdci_std-segment-matching-service-app-meta:matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","textRange":{"startLine":104,"endLine":104,"startOffset":20,"endOffset":32},"msg":"Returned value."}]}],"resolution":"FIXED","status":"CLOSED","message":"Refactor this method to not always return the same value.","effort":"4min","debt":"4min","author":"shichao.shan@ecarx.com.cn","tags":[],"creationDate":"2021-07-27T16:19:30+0800","updateDate":"2021-08-17T10:30:36+0800","closeDate":"2021-08-17T10:30:36+0800","type":"CODE_SMELL","scope":"MAIN"},{"key":"AXtSCNUaBV_LB6M9s77_","rule":"java:S3516","severity":"BLOCKER","component":"stdci_std-segment-matching-service-app-meta:src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","project":"stdci_std-segment-matching-service-app-meta","hash":"f69a44a25855a41d7902b3bbadf667ca","textRange":{"startLine":97,"endLine":97,"startOffset":26,"endOffset":54},"flows":[{"locations":[{"component":"stdci_std-segment-matching-service-app-meta:src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","textRange":{"startLine":108,"endLine":108,"startOffset":8,"endOffset":20},"msg":"Returned value."},{"component":"stdci_std-segment-matching-service-app-meta:src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","textRange":{"startLine":104,"endLine":104,"startOffset":20,"endOffset":32},"msg":"Returned value."}]}],"resolution":"FIXED","status":"CLOSED","message":"Refactor this method to not always return the same value.","effort":"4min","debt":"4min","author":"shichao.shan@ecarx.com.cn","tags":[],"creationDate":"2021-07-27T16:19:30+0800","updateDate":"2021-08-17T17:52:30+0800","closeDate":"2021-08-17T17:52:30+0800","type":"CODE_SMELL","scope":"MAIN"}],"components":[{"key":"stdci_std-segment-matching-service-app-meta","enabled":true,"qualifier":"TRK","name":"std-segment-matching-service-app-meta","longName":"std-segment-matching-service-app-meta"},{"key":"stdci_std-segment-matching-service-app-meta:src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","enabled":false,"qualifier":"FIL","name":"OsmClientServiceTest.java","longName":"src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","path":"src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java"},{"key":"stdci_std-segment-matching-service-app-meta:segment-matching-service/matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","enabled":true,"qualifier":"FIL","name":"OsmClientServiceTest.java","longName":"segment-matching-service/matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","path":"segment-matching-service/matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java"},{"key":"stdci_std-segment-matching-service-app-meta:matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","enabled":false,"qualifier":"FIL","name":"OsmClientServiceTest.java","longName":"matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java","path":"matching-service/src/test/java/com/ecarx/roadinsight/matching/service/service/OsmClientServiceTest.java"}],"facets":[]}'
    # i = s.split('FIXED')
    # print(len(i) - 1)